package core

import (
	"fmt"
	"gopkg.in/yaml.v2"
	"gvb_server/config"
	"gvb_server/global"
	"gvb_server/models/ctype"
	"io/fs"
	"io/ioutil"
	"log"
	"os"
)

const ConfigFile = "settings.yaml"

func InitConfig() {
	c := &config.Config{}
	yamlConf, err := ioutil.ReadFile(ConfigFile)
	if err != nil {
		panic(fmt.Errorf("get yamlConf error: %s", err))
	}
	err = yaml.Unmarshal(yamlConf, c)
	if err != nil {
		log.Fatalf("config Init Unmarshal: %v", err)
	}
	log.Println("config Init success")
	global.Config = c
	// 如果文件是本地上传那么先创建文件夹
	if global.Config.System.Storage == ctype.LOCAL {
		basePath := global.Config.Local.StorePath
		_, err = os.ReadDir(basePath)
		if err != nil {
			err = os.MkdirAll(basePath, fs.ModePerm)
			if err != nil {
				global.Log.Error(err)
			}
		}
	}
}

func SetYaml() {
	byteData, err := yaml.Marshal(global.Config)
	if err != nil {
		global.Log.Error(err)
		return
	}
	err = ioutil.WriteFile(ConfigFile, byteData, fs.ModePerm)
	if err != nil {
		global.Log.Error(err)
		return
	}
	global.Log.Info("配置修改成功")
}
